package com.work.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.work.common.ctx.DataPermissionCtx;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;
import java.time.LocalDateTime;

@Slf4j
@Configuration
@MapperScan("com.work.mapper")
public class MybatisConfig implements MetaObjectHandler {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(sqlInterceptor());
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    //    sql拦截
    public InnerInterceptor sqlInterceptor() {
        return new InnerInterceptor() {
            @Override
            public void beforeQuery(Executor executor, MappedStatement ms,
                                    Object parameter, RowBounds rowBounds,
                                    ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
//                TODO 获取注解并处理注解的逻辑
                final String dataPermission = DataPermissionCtx.getDataPermission();
                final PluginUtils.MPBoundSql mbs = PluginUtils.mpBoundSql(boundSql);
//                获取sql
                final String sql = mbs.sql();
//                修改sql 。。。
//                假设这里修改了
//                mbs.sql(sql);  //通过这个方法将新的sql传递进去
                InnerInterceptor.super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
            }
        };
    }

    @Override
    public void insertFill(MetaObject metaObject) {
//        自动填充
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
//        自动填充
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

}
